using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;

namespace GEContentPipeline
{
    /// <summary>
    /// </summary>
    [ContentProcessor(DisplayName = "GEContentPipeline.ModelContentProcessor")]
    public class ModelContentProcessor : ModelProcessor
    {
        public override ModelContent Process(NodeContent input, ContentProcessorContext context)
        {
            Dictionary<string, GEAnimationClip> animations = new Dictionary<string, GEAnimationClip>();

            foreach (KeyValuePair<string, AnimationContent> anim in input.Animations)
            {
                animations.Add(anim.Key, ProcessAnimation(anim.Value));
            }

            ModelContent model = base.Process(input, context);

            model.Tag = animations;

            
            throw new InvalidContentException(input.Animations.Keys.Count.ToString());

            return model;
        }

        private static GEAnimationClip ProcessAnimation(AnimationContent content)
        {
            List<GEKeyframe> keyframes = new List<GEKeyframe>();

            foreach (KeyValuePair<string, AnimationChannel> channel in content.Channels)
            {
                foreach (AnimationKeyframe keyframe in channel.Value)
                {
                    keyframes.Add(new GEKeyframe(keyframe.Time, keyframe.Transform));
                }
            }
            
            keyframes.Sort(CompareKeyFrames);

            if(keyframes.Count == 0)
                throw new InvalidContentException("No animations");

            return new GEAnimationClip(content.Duration, keyframes);
        }

        private static int CompareKeyFrames(GEKeyframe a, GEKeyframe b)
        {
            return a.TimeSpan.CompareTo(b.TimeSpan);
        }
    }
}